﻿# coding: UTF-8
# Name:
# Author: LYC
# Created:

import sys
import thread
import random
import Queue
import time

class Actor(object):
    def __init__(self, name, out_queue):
        super(Actor, self).__init__()

        self.name = name
        self.out_queue = out_queue

    def output(self, str_line, *args):
        self.out_queue.put(str_line % args)

    def ready(self):
        self.output(u"%s is ready.", self.name)

    def waiting(self):
        self.output(u"%s is waiting.", self.name)

    def work(self, beltline):
        return None

    def done(self):
        time.sleep(random.randint(2, 5))

    def __call__(self, lock, beltline):
        self.enable = True

        self.ready()

        while self.enable:
            if lock.locked():
                self.waiting()

            if lock.acquire():
                self.work(beltline)
                lock.release()

            self.done()


class Producer(Actor):
    def __init__(self, out_queue):
        super(Producer, self).__init__("Producer", out_queue)

    def work(self, beltline):
        self.output(u"%s is working on the thread %d", self.name, thread.get_ident())

        for i in xrange(random.randint(1, 3)):
            produce = random.random()
            beltline.append(produce)
            self.output(u"%s created a new number %f", self.name, produce)

class Consumer(Actor):
    def __init__(self, out_queue):
        super(Consumer, self).__init__("Consumer", out_queue)

    def work(self, beltline):
        self.output(u"%s is working on the thread %d", self.name, thread.get_ident())

        while beltline:
            produce = beltline.popleft()
            self.output(u"%s is dealing number %f", self.name, produce)

def main(argv):
    lock = thread.allocate()
    beltline = Queue.deque()
    out_queue = Queue.Queue()

    producer = Producer(out_queue)
    consumer = Consumer(out_queue)

    thread.start_new(producer, (lock, beltline))
    thread.start_new(consumer, (lock, beltline))

    while True:
        print out_queue.get()


if __name__ == '__main__':
    main(sys.argv)
